package com.ruoyi.system.utils.tengcent;

import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.ocr.v20181119.OcrClient;
import com.tencentcloudapi.ocr.v20181119.models.*;
import org.apache.commons.io.FileUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Base64;

public class TencentOcrService {

    private final String secretId;
    private final String secretKey;
    private final String region;
    private final String tempFilePath;

    public TencentOcrService(String secretId, String secretKey, String region, String tempFilePath) {
        this.secretId = secretId;
        this.secretKey = secretKey;
        this.region = region;
        this.tempFilePath = tempFilePath;
    }

    /**
     * 创建OCR客户端
     */
    private OcrClient createClient() {
        Credential cred = new Credential(secretId, secretKey);
        HttpProfile httpProfile = new HttpProfile();
        httpProfile.setEndpoint("ocr.tencentcloudapi.com");
        ClientProfile clientProfile = new ClientProfile();
        clientProfile.setHttpProfile(httpProfile);
        return new OcrClient(cred, region, clientProfile);
    }

    /**
     * 识别PDF文件内容
     * @param pdfFile 上传的PDF文件
     * @return 识别结果
     */
    public String recognizePdf(MultipartFile pdfFile) throws TencentCloudSDKException, IOException {
        // 1. 将MultipartFile保存为临时文件
        File tempFile = saveMultipartFileToTemp(pdfFile);

        // 2. 读取文件内容并Base64编码
        byte[] fileBytes = Files.readAllBytes(tempFile.toPath());
        String fileBase64 = Base64.getEncoder().encodeToString(fileBytes);

        // 3. 创建OCR请求
        RecognizeTableOCRRequest req = new RecognizeTableOCRRequest();
        req.setImageBase64(fileBase64);
        req.setPdfPageNumber(1L); // 设置PDF页码，1表示第一页

        // 4. 调用腾讯云OCR接口
        OcrClient client = createClient();
        RecognizeTableOCRResponse resp = client.RecognizeTableOCR(req);

        // 5. 删除临时文件
        tempFile.delete();

        // 6. 返回识别结果
//        return resp.getTextDetections() != null ?
//                resp.getTextDetections()[0].getDetectedText() : "未识别到文本";

        return resp.getTableDetections() != null ?
                String.valueOf(resp.getTableDetections()[0].getCells()) : null;
    }

    /**
     * 将MultipartFile保存为临时文件
     */
    private File saveMultipartFileToTemp(MultipartFile file) throws IOException {
        // 确保临时目录存在
        Path tempDir = Paths.get(tempFilePath);
        if (!Files.exists(tempDir)) {
            Files.createDirectories(tempDir);
        }

        // 生成临时文件名
        String originalFilename = file.getOriginalFilename();
        String tempFileName = "tencent_ocr_temp_" + System.currentTimeMillis() +
                (originalFilename != null ? originalFilename.substring(originalFilename.lastIndexOf('.')) : ".pdf");

        // 保存文件
        File tempFile = new File(tempFilePath + File.separator + tempFileName);
        file.transferTo(tempFile);

        return tempFile;
    }
}
